package com.tyanxie.asd.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.ConfigurationCompat
import androidx.recyclerview.widget.RecyclerView
import com.tyanxie.asd.Constant
import com.tyanxie.asd.R
import com.tyanxie.asd.activity.HistoryActivity
import com.tyanxie.asd.model.SugarNumber
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.SimpleDateFormat
import java.util.*

class HistoryAdapter(private val activity: HistoryActivity, private val sugarNumbers: MutableList<SugarNumber>) :
    RecyclerView.Adapter<HistoryAdapter.HistoryViewHolder>() {

    companion object {
        val tvIds = listOf(
            R.id.hb_value1_tv, R.id.hb_value2_tv, R.id.hb_value3_tv, R.id.hb_value4_tv, R.id.hb_value5_tv
        )
    }

    private val dateFormat = SimpleDateFormat(
        "MM-dd HH:mm",
        ConfigurationCompat.getLocales(activity.resources.configuration)[0]
    )

    /**
     * 清空数据
     */
    @SuppressLint("NotifyDataSetChanged")
    fun clear() {
        this.sugarNumbers.clear()
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        HistoryViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.history_block, parent, false)
        )

    override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
        holder.itemView.apply {
            val item = sugarNumbers[position]

            findViewById<TextView>(R.id.hb_type_tv)?.text = activity.getString(Constant.apples[item.type])
            findViewById<TextView>(R.id.hb_time_tv)?.text = dateFormat.format(Date(item.createTime))

            if (item.sugarEntities != null) {
                val items = item.sugarEntities!!
                var idx = 0
                for (it in items) {
                    if (idx >= 5) {
                        break
                    }
                    BigDecimal(items[idx].value).apply {
                        findViewById<TextView>(tvIds[idx]).text =
                            activity.getString(
                                R.string.ordered_list_item,
                                idx + 1, setScale(1, RoundingMode.HALF_UP).toString()
                            )
                    }
                    idx++
                }
            }
        }
    }

    override fun getItemCount() = sugarNumbers.size

    class HistoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}